<?php
/**
 * Created by PhpStorm.
 * User: luo
 * Date: 2018/9/30
 * Time: 9:09
 */

namespace app\controllers;

use app\tools\Re;
use Qiniu\Auth;
use Yii;

class QiniuController extends BaseController
{
    public function actionGetToken($is_private = 0){
        $qiniu = Yii::$app->params['qiniu'];
        $auth = new Auth($qiniu['access_key'], $qiniu['secret_key']);
        if($is_private == 1){
            $bucket = $qiniu['private_bucket'];
            $url    = $qiniu['private_url'];
        }else{
            $bucket = $qiniu['bucket'];
            $url    = $qiniu['url'];
        }
        $key = Yii::$app->request->post('key', '');
        if($key){
            $bucket = $bucket . ':'.$key;
        }
        $policy = [
            'saveKey'    => '$(etag)$(ext)',
            'returnBody' => '{"key":$(key),"domain":"' . $url . '","size":$(fsize),"w": $(imageInfo.width),"h":$(imageInfo.height),"hash":$(etag)}'
        ];
        $token = $auth->uploadToken($bucket, null, 36000, $policy);
        return Re::data(['token' => $token]);
    }

    public function actionGetPrivateUrl($url){
        $qiniu = Yii::$app->params['qiniu'];
        // 构建Auth对象
        $auth = new Auth($qiniu['access_key'], $qiniu['secret_key']);
        // 私有空间中的外链 http://<domain>/<file_key>
        // 对链接进行签名
        $signedUrl = $auth->privateDownloadUrl($url);
        return Re::data(['url'=>$signedUrl]);
    }
}
